package com.hsteach.service.patrol;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hsteach.common.constant.HttpStatus;
import com.hsteach.common.core.domain.AjaxResult;
import com.hsteach.common.core.page.TableDataInfo;
import com.hsteach.common.exception.ServiceException;
import com.hsteach.dao.domain.patrol.Behavior;
import com.hsteach.dao.domain.patrol.BehaviorCategory;
import com.hsteach.dao.domain.patrol.InspectionDetail;
import com.hsteach.dao.mapper.BehaviorCategoryMapper;
import com.hsteach.dao.mapper.BehaviorMapper;
import com.hsteach.enums.CategoryTypeEnum;
import com.hsteach.web.controller.patrol.dto.BehaviorCategoryDTO;
import com.hsteach.web.controller.patrol.dto.QueryBehaviorDTO;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author mgb
 * @version BehaviorCategoryService, java v1.0 2023-11-14 22:14 EXP $
 */
@Service
public class BehaviorCategoryService {

    @Resource
    public BehaviorCategoryMapper behaviorCategoryMapper;

    @Resource
    public BehaviorMapper behaviorMapper;

    @Autowired
    public InspectionService inspectionService;

    /**
     * 添加行为分类
     *
     * @param behaviorCategory
     * @return
     */
    public TableDataInfo addCategory(BehaviorCategory behaviorCategory) {
        if (StringUtils.isEmpty(behaviorCategory.getOrgCode())){
            throw new ServiceException("orgCode不能为空");
        }
        TableDataInfo tableDataInfo = new TableDataInfo();

        // 1.查询该行为分类是否存在
        BehaviorCategory queryResult = behaviorCategoryMapper.getCategory(behaviorCategory.getFirstCategory(), behaviorCategory.getSecondCategory(), behaviorCategory.getOrgCode());
        if (Objects.nonNull(queryResult)) {
            tableDataInfo.setCode(HttpStatus.ERROR);
            tableDataInfo.setMsg("分类已存在，不能重复添加");
            return tableDataInfo;
        }
        if (StringUtils.isBlank(behaviorCategory.getFirstCategory())) {
            tableDataInfo.setMsg("分类名称不能为空！");
            return tableDataInfo;
        }
        if (CategoryTypeEnum.SUBSET_LEVEL.getCode() == behaviorCategory.getCateGoryType()) {
            if (StringUtils.isBlank(behaviorCategory.getSecondCategory())) {
                tableDataInfo.setMsg("行为分类不能为空！");
                return tableDataInfo;
            }
        }

        int sort = 0;
        // 通过分类查询
        List<BehaviorCategory> behaviorCategoryList = behaviorCategoryMapper.queryAllCategory(behaviorCategory.getOrgCode());
        if (!CollectionUtils.isEmpty(behaviorCategoryList)) {
            sort = behaviorCategoryList.size() + 1;
        }

        // 执行插入数据
        int insertResult = behaviorCategoryMapper.insertCategory(behaviorCategory.getFirstCategory(), behaviorCategory.getSecondCategory(), sort,behaviorCategory.getOrgCode());
        if (insertResult > 0) {
            tableDataInfo.setCode(200);
            tableDataInfo.setTotal(insertResult);
            tableDataInfo.setMsg("添加成功");
        }
        return tableDataInfo;
    }

    /**
     * 添加细则
     *
     * @param behaviorDetail
     * @return
     */
    public TableDataInfo addBehavior(BehaviorDetail behaviorDetail) {
        if (StringUtils.isBlank(behaviorDetail.getOrgCode())) {
           throw new ServiceException("orgCode不能为空");
        }
        TableDataInfo tableDataInfo = new TableDataInfo();
        // 查询对应的分类是否存在
        BehaviorCategory behaviorCategory = behaviorCategoryMapper.getCategory(behaviorDetail.getCategory(), behaviorDetail.getCategoryName(), behaviorDetail.getOrgCode());
        if (Objects.isNull(behaviorCategory)) {
            tableDataInfo.setCode(400);
            tableDataInfo.setMsg("分类不存在");
        }
        behaviorDetail.setCategoryId(behaviorCategory.getId());
        // 存在新增
        int insertResult = behaviorMapper.addBehavior(behaviorDetail);
        if (insertResult > 0) {
            tableDataInfo.setCode(200);
            tableDataInfo.setTotal(insertResult);
            tableDataInfo.setMsg("添加成功");
        }
        return tableDataInfo;
    }

    /**
     * 编辑细则
     *
     * @param behaviorDetail
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public TableDataInfo updateBehavior(BehaviorDetail behaviorDetail) {
        if (StringUtils.isBlank(behaviorDetail.getOrgCode())) {
            throw new ServiceException("orgCode不能为空");
        }
        TableDataInfo tableDataInfo = new TableDataInfo();
        // 查询对应的分类是否存在
        List<BehaviorCategory> behaviorCategory = behaviorCategoryMapper.queryCategory(behaviorDetail.getCategory(), behaviorDetail.getCategoryName(), behaviorDetail.getOrgCode());
        if (!CollectionUtils.isEmpty(behaviorCategory)) {
            tableDataInfo.setCode(400);
            tableDataInfo.setMsg("分类不存在");
        }
        // 存在新增
        int insertResult = behaviorMapper.updateBehavior(behaviorDetail);
        // 更新所有巡查信息
        Behavior behavior = new Behavior();
        behavior.setId(behaviorDetail.getId());
        behavior.setCategoryName(behaviorDetail.getCategoryName());
        behavior.setScore(behaviorDetail.getScore());
        behavior.setDescription(behaviorDetail.getDescription());

        inspectionService.updateOrdinanceById(Collections.singletonList(behavior));
        if (insertResult > 0) {
            tableDataInfo.setCode(200);
            tableDataInfo.setTotal(insertResult);
            tableDataInfo.setMsg("修改成功");
        }
        return tableDataInfo;
    }

    /**
     * 删除分类
     *
     * @param id
     * @return
     */
    public AjaxResult deleteCategory(int id) {
        BehaviorCategory categoryById = behaviorCategoryMapper.getCategoryById(id);
        if (Objects.isNull(categoryById)) {
           return AjaxResult.error("分类不存在！");
        }
        // 执行删除
        int result = behaviorCategoryMapper.deleteCategory(id);
        // 删除该分类下所有的细则
        List<Behavior> behaviors = behaviorMapper.queryCategoryByParentId(categoryById.getId());
        if (!CollectionUtils.isEmpty(behaviors)) {
            int resultDetail = behaviorMapper.deleteInfoByParentId(categoryById.getId());
        }

        return AjaxResult.success();

    }

    /**
     * 查询行为分类
     *
     * @return
     */
    public Map<String, List<BehaviorCategory>> queryCategory(String firstCategory,String orgCode) {
        if (StringUtils.isBlank(orgCode)) {
            throw new ServiceException("orgCode不能为空");
        }
        List<BehaviorCategory> behaviorCategories = behaviorCategoryMapper.queryCategory(firstCategory, null,orgCode);
        Map<String, List<BehaviorCategory>> result = behaviorCategories.stream()
                .filter(behaviorCategory -> behaviorCategory.getFirstCategory() != null)
                .collect(Collectors.groupingBy(BehaviorCategory::getFirstCategory));
        return result;
    }
//    public List<BehaviorCategory> queryCategory(String firstCategory) {
//        List<BehaviorCategory> behaviorCategories = behaviorCategoryMapper.queryCategory(firstCategory, null);
//        List<BehaviorCategory> collect = behaviorCategories.stream().filter(behaviorCategory -> StringUtils.isNotEmpty(behaviorCategory.getSecondCategory())).collect(Collectors.toList());
//        List<BehaviorCategory> result = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(behaviorCategories)) {
//
//            for (BehaviorCategory behaviorCategory : behaviorCategories) {
//                if (StringUtils.isBlank(behaviorCategory.getSecondCategory())) {
//                    List<BehaviorCategory> list = new ArrayList<>();
//                    for (BehaviorCategory category : collect) {
//                        if (behaviorCategory.getFirstCategory().equals(category.getFirstCategory())) {
//                            list.add(category);
//                        }
//                    }
//
//                    behaviorCategory.setCategoryList(list);
//                    result.add(behaviorCategory);
//                }
//            }
//        }
//
//        return result;
//    }

    public Map<Integer, Behavior> getBehaviorById(List<Integer> ids) {
        List<Behavior> behaviors = behaviorMapper.getBehaviorById(ids);
        Map<Integer, Behavior> behaviorToIdMap = behaviors.stream().collect(Collectors.toMap(Behavior::getId, Function.identity()));
        return behaviorToIdMap;
    }

    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateCategory(BehaviorCategory behaviorCategory) {
        if (StringUtils.isEmpty(behaviorCategory.getOrgCode())) {
            throw new ServiceException("orgCode不能为空");
        }

        // 1. 根据id查询
        BehaviorCategory sourceCategory = behaviorCategoryMapper.queryCategoryById(behaviorCategory.getId());
        if (Objects.isNull(sourceCategory)) {
            return AjaxResult.error("分类不存在");
        }
        // 查询该行为分类是否存在
        List<BehaviorCategory> queryResult = behaviorCategoryMapper.queryCategory(behaviorCategory.getFirstCategory(), behaviorCategory.getSecondCategory(), behaviorCategory.getOrgCode());
        if (!CollectionUtils.isEmpty(queryResult)) {
            return AjaxResult.error("不能和原分类相同,请重新修改");
        }
        List<BehaviorCategory> needUpdateList = behaviorCategoryMapper.queryCategory(sourceCategory.getFirstCategory(), sourceCategory.getSecondCategory(),sourceCategory.getOrgCode());

        if (!CollectionUtils.isEmpty(needUpdateList)) {
            needUpdateList = needUpdateList.stream().map(needUpdateBehaviorCategory -> {
                needUpdateBehaviorCategory.setFirstCategory(behaviorCategory.getFirstCategory());
                if (StringUtils.isNotBlank(behaviorCategory.getSecondCategory())) {
                    needUpdateBehaviorCategory.setSecondCategory(behaviorCategory.getSecondCategory());
                }
                return needUpdateBehaviorCategory;
            }).collect(Collectors.toList());
        }
        // 执行更新
        for (BehaviorCategory category : needUpdateList) {
            behaviorCategoryMapper.updateCategory(category);
            if (!StringUtils.isBlank(behaviorCategory.getSecondCategory()) || !StringUtils.isBlank(behaviorCategory.getFirstCategory())) {
                behaviorMapper.updateBehaviorByCategoryId(category.getId(), behaviorCategory.getFirstCategory(), behaviorCategory.getSecondCategory(),behaviorCategory.getOrgCode());
                List<Behavior> behaviors = behaviorMapper.queryCategoryByParentIdAndOrgCode(category.getId(),behaviorCategory.getOrgCode());
                if (!CollectionUtils.isEmpty(behaviors)) {
                    for (Behavior behavior : behaviors) {
                        behavior.setCategory(behaviorCategory.getFirstCategory());
                        behavior.setCategoryName(behaviorCategory.getSecondCategory());
                    }
                    // 更新所有巡查信息
                    inspectionService.updateOrdinanceById(behaviors);
                }
            }
        }

        return AjaxResult.success("修改成功");
    }

    public AjaxResult updateCategorySort(List<BehaviorCategoryDTO> behaviorCategoryDTOS) {
        int targetResult = 0;
        for (BehaviorCategoryDTO behaviorCategoryDTO : behaviorCategoryDTOS) {
            targetResult = behaviorCategoryMapper.updateCategorySort(behaviorCategoryDTO);

        }
        if (targetResult > 0) {
            return AjaxResult.success();
        }
        return null;
    }

    public TableDataInfo<Behavior> queryBehavior(QueryBehaviorDTO queryBehaviorDTO) {
        if (StringUtils.isBlank(queryBehaviorDTO.getOrgCode())){
            throw new ServiceException("orgCode不能为空");
        }
        PageHelper.startPage(queryBehaviorDTO.getPageNum(), queryBehaviorDTO.getPageSize());
        List<Behavior> behaviors = behaviorMapper.queryBehavior(queryBehaviorDTO.getFirstCategory(), queryBehaviorDTO.getSecondCategory(), queryBehaviorDTO.getKeyword(), queryBehaviorDTO.getOrgCode());
        //给细则按照所属分类进行排序 ====START
        List<Integer> categoryIds = behaviors.stream()
                .filter(Objects::nonNull)
                .map(Behavior::getCategoryId)
                .distinct()
                .collect(Collectors.toList());
        Map<Integer, Map<String, Integer>> categoryIdAndSortMap = behaviorCategoryMapper.selectSortMapByIds(categoryIds);
        behaviors.forEach(item->{
            Map<String, Integer> idSortMap = categoryIdAndSortMap.get(item.getCategoryId());
            if (ObjectUtils.isNotEmpty(idSortMap)) {
                Integer sort = idSortMap.get("sort");
                item.setCategorySort(sort);
            }
        });
        behaviors.sort(Comparator.comparing(Behavior::getCategorySort));
        //给细则按照所属分类进行排序 ====END
//        Long total = new PageInfo<Behavior>().getTotal();
        Long total = new PageInfo<>(behaviors).getTotal();
        TableDataInfo<Behavior> behaviorTableDataInfo = new TableDataInfo<>(behaviors, total);
        return behaviorTableDataInfo;
    }

    public AjaxResult deleteBehavior(int id) {
        // 通过细则id去查询评分是否有使用，若有则不能删除
        List<InspectionDetail> inspections = inspectionService.queryInspectionByBehaviorId(id);
        if (!CollectionUtils.isEmpty(inspections)) {
            return AjaxResult.error("该细则有使用，不能删除");
        }
        return AjaxResult.success("删除成功", behaviorMapper.deleteBehavior(id));
    }
}
